package com.guangfeng.yql.comm.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * netty 图片上传 ， todo 文件上传没问题，图片路径返回暂时拿不到
 */
@ChannelHandler.Sharable
@Component
@Slf4j
public class UploadFileHandler extends SimpleChannelInboundHandler<BinaryWebSocketFrame> {

//    @Autowired
//    CommonController commonController;


    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        log.info("图片上传开始链接 ");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BinaryWebSocketFrame msg) throws Exception {
        ByteBuf buf = msg.content();
        ArrayList<Byte> list = new ArrayList<>();
        buf.forEachByte(list::add);
        byte[] bytes = new byte[list.size()];
        for (int i = 0; i < list.size(); i++) {
            bytes[i] = list.get(i);
        }
//        String name = SnUtils.orderNo() + ".jpg";
//        MockMultipartFile file = new MockMultipartFile(name, name, null, bytes);
//        RestResponse response = commonController.add1(file);
//        String url = response.getData().toString();
//        ByteBuf buffer = Unpooled.wrappedBuffer(url.getBytes());
//        ctx.writeAndFlush(buffer);
//        ctx.channel().close();
//        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error(cause.getMessage(), cause);
        super.exceptionCaught(ctx, cause);
    }
}
